import { defineStore } from "pinia";
import { loginApi, getUserInfoApi } from "../api/user";

// 写法 选项式
// 组合式
const useUserStore = defineStore("user", {
  // options
  state: () => ({
    token: "",
    userinfo: null,
  }),
  //   方法：同步和异步
  actions: {
    //1.发送请求获取到数据 存储 token
    async getUserToken({ username, password }) {
      try {
        const res = await loginApi({ username, password });
        // 存储token
        this.token = res.access_token;
        this.getUserInfo();
        // console.log(this.token);
        // 本地存储
        return Promise.resolve(true);
      } catch (error) {
        return Promise.reject(false);
      }
    }, //获取用户信息
    async getUserInfo() {
      try {
        const res = await getUserInfoApi();
        console.log(res);
        // 存储
        this.userinfo = res;
        return Promise.resolve(true);
      } catch (error) {
        console.log(error);
        return Promise.reject(false);
      }
    },
  },
  //   计算属性
  getters: {},

  persist: {
    enabled: true,
    strategies: [
      {
        key: "user",
        storage: localStorage,
      },
    ],
  },
});

export default useUserStore;
